// 初始化一级类目
initClass(0, {
    "categoryLevel": 1
});
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
var pointId = 0;
//积分管理


/*跳转到添加页面*/
function jumpToAdd(title, url) {
    sessionStorage.setItem("pointId",0);
    pointId = 0;
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

// 初始化三级类目
function initClass(level, data) {
    $.ajax({
        url: root.goodsInter.categoryByParam,
        cache: false, //禁用缓存
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        type: "POST",
        data: data,
        success: function (data) {
            if (data != null && data.data.length > 0) {
                // 初始化一级类目
                if (level == 0) {
                    for (var i = 0; i < data.data.length; i++) {
                        $("#oneCategoryId").append("<option value='" + data.data[i].category_id + "'>" + data.data[i].category_name + "</option>");
                    }
                } else if (level == 1) {
                    for (var i = 0; i < data.data.length; i++) {
                        $("#twoCategoryId").append("<option value='" + data.data[i].category_id + "'>" + data.data[i].category_name + "</option>");
                    }
                } else if (level == 2) {
                    for (var i = 0; i < data.data.length; i++) {
                        $("#threeCategoryId").append("<option value='" + data.data[i].category_id + "'>" + data.data[i].category_name + "</option>");
                    }
                } else if (level == 3) {
                    for (var i = 0; i < data.data.length; i++) {
                        $("#fourCategoryId").append("<option value='" + data.data[i].category_id + "'>" + data.data[i].category_name + "</option>");
                    }
                }
            }
        },
        error: function () {
            console.log("!!!!获取商品类目异常-商品后台!!!!");
            layer.msg('获取商品类目异常-商品后台', {
                icon: 2,
                time: 3000
            });
        }
    });
}

$("#gradeId").change(function () {
    $("#pageNum").val(1);
})

$("#oneCategoryId").change(function () {
    changeClass(0);
    $("#pageNum").val(1);
});
$("#twoCategoryId").change(function () {
    changeClass(1);
    $("#pageNum").val(1);
});

$("#threeCategoryId").change(function () {
    changeClass(2);
    $("#pageNum").val(1);
})


// 类目选择变动函数
function changeClass(level) {
    // 一级类目点击事件,重新加载二级类目,清空三级类目内容
    if (level == 0) {
        $("#twoCategoryId").empty();
        $("#twoCategoryId").append("<option value=''>请选择二级品类</option>");
        $("#threeCategoryId").empty();
        $("#threeCategoryId").append("<option value=''>请选择三级品类</option>");
        $("#fourCategoryId").empty();
        $("#fourCategoryId").append("<option value=''>请选择四级品类</option>");
        if ($("#oneCategoryId").val() != "") {
            initClass(1, {
                "parentCateId": $("#oneCategoryId").val()
            })
        }
    }
    // 二级类目点击事件,重新加载三级类目
    if (level == 1) {
        $("#threeCategoryId").empty();
        $("#threeCategoryId").append("<option value=''>请选择三级品类</option>");
        $("#fourCategoryId").empty();
        $("#fourCategoryId").append("<option value=''>请选择四级品类</option>");
        if ($("#twoCategoryId").val() != "") {
            initClass(2, {
                "parentCateId": $("#twoCategoryId").val()
            })
        }
    }
    // 二级类目点击事件,重新加载三级类目
    if (level == 2) {
        $("#fourCategoryId").empty();
        $("#fourCategoryId").append("<option value=''>请选择四级品类</option>");
        if ($("#threeCategoryId").val() != "") {
            initClass(3, {
                "parentCateId": $("#threeCategoryId").val()
            })
        }
    }
}

// 初始化等级
initLevel();

function initLevel() {
    $.ajax({
        url: root.member.getLevelsByPage,
        cache: false, //禁用缓存
        contentType: 'application/x-www-form-urlencoded',
        type: "post",
        data: {pageNum: 1, pageSize: 100},
        success: function (data) {
            if (data != null && data.data.result.length > 0) {
                // 初始化一级类目
                for (var i = 0; i < data.data.result.length; i++) {
                    $("#gradeId").append('<option value="' + data.data.result[i].gradeId + '">' + data.data.result[i].gradeName + '</option>');
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
            console.log("!!!!会员等级系统异常!!!!");
            layer.msg('会员等级系统异常!', {
                icon: 2,
                time: 3000
            });
            layer.closeAll();
        }
    });
}

function initTable11() {
    $.ajax({
        url:root.member.getPointsByPage,
        cache: false,  //禁用缓存
        cache: false, //禁用缓存
        contentType: 'application/x-www-form-urlencoded',
        type: "post",
        data: {
            pageNum: 1,
            pageSize: 10,
            oneCategoryId: $("#oneCategoryId").val(),
            twoCategoryId:$("#twoCategoryId").val(),
            threeCategoryId:$("#threeCategoryId").val(),
            gradeId:$("#gradeId").val(),
            state:$("#states").val()
        },
        success: function (data) {
            initTabls(data.data.result, 0);
            $('.M-box3').pagination({
                pageCount: data.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url:root.member.getPointsByPage,
                        cache: false,  //禁用缓存
                        cache: false, //禁用缓存
                        contentType: 'application/x-www-form-urlencoded',
                        type: "post",
                        data: {
                            pageNum: api.getCurrent(),
                            pageSize: 10,
                            oneCategoryId: $("#oneCategoryId").val(),
                            twoCategoryId:$("#twoCategoryId").val(),
                            threeCategoryId:$("#threeCategoryId").val(),
                            gradeId:$("#gradeId").val(),
                            state:$("#states").val()
                        },
                        success: function (result) {
                            initTabls(result.data.result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

// 渲染table
function initTabls(data) {

    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0,dataSource.length);//清空数组


    $.each(data, function (i, field) {
        var rowData = new Array();
        rowData.push(field.oneCategoryName);//一级品类
        rowData.push(field.twoCategoryName);//二级品类
        rowData.push(field.threeCategoryName);//三级品类
        rowData.push(field.fourCategoryName ? field.fourCategoryName : "");//四级品类
        rowData.push(field.integralCoefficient);//积分系数
        rowData.push(field.state);//状态
        rowData.push(field.rulerId);//主键
        rowData.push(field.index);
        rowData.push(field.oneCategoryId);//一级品类
        rowData.push(field.twoCategoryId);//二级品类
        rowData.push(field.threeCategoryId);//三级品类
        rowData.push(field.fourCategoryId);//四级品类
        dataSource.push(rowData);

    });

    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#pointTable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#pointTable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[7]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },


                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 5
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if (row[5] == 10) {
                            val =  '<span class="powerButton 446"><a id="state-' + row[6] + '" onclick="updateState(' + row[6] + ',' + row[5] + ',' + row[8] + ',' + row[9] + ',' + row[10] + ',' + row[11] + ')">启用</a></span>';
                        } else {
                            val =  '<span class="powerButton 446"><a id="state-' + row[6] + '" onclick="updateState(' + row[6] + ',' + row[5] + ',' + row[8] + ',' + row[9] + ',' + row[10] + ',' + row[11] + ')">禁用</a></span>';
                        }
                        return val;
                    },
                    "targets":6
                },

                {
                    "render": function (data, type, row, meta) {
                        var val='';
                        val= '<a class="powerButton 447" onclick="editPoint(\'修改品类积分规则\',\'pointDetail.html\',\''+row[6]+'\')">修改</a>';
                        return val;
                    },
                    "targets":7
                }


            ]
        });
//权限控制函数
        power()
    };
}

// 编辑
/*function editPoint(id) {
    pointId = id;
    jumpToEdit('编辑规则', 'pointDetail.html')
}*/
function editPoint(title,url,id){
    console.log(id)
    sessionStorage.setItem("pointId",id);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}


// 禁用启用
function updateState(id, state,oneid,twoid,threeid,fourCategoryId) {
    var tostate = 0;
    if (state == 10) {
        tostate = 20;
    } else {
        tostate = 10;
    }
    $.ajax({
        url: root.member.updatePointState,
        cache: false, //禁用缓存
        type: "post",
        jsonType: "json",
        data: {
            "rulerId": id,
            "state": tostate,
            "oneCategoryId":oneid,
            "twoCategoryId":twoid,
            "threeCategoryId":threeid,
            "fourCategoryId":fourCategoryId,
        },
        success: function (data) {
            if (data.errorCode == 0) {
                if (tostate == 10) {
                    $("#state-" + id).parent().html('<a id="state-' + id + '" onclick="updateState(' + id + ',10,' + oneid + ',' + twoid + ',' + threeid + ',' + fourCategoryId + ')">启用</a>');
                } else {
                    $("#state-" + id).parent().html('<a id="state-' + id + '" onclick="updateState(' + id + ',20,' + oneid + ',' + twoid + ',' + threeid + ',' + fourCategoryId + ')">禁用</a>');
                }
            } else {
                layer.msg(data.msg, {
                    icon: 2,
                    time: 3000
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
            console.log("!!!!会员等级系统异常!!!!");
            layer.msg('会员等级系统异常!', {
                icon: 2,
                time: 3000
            });
            layer.closeAll();
        }
    });

}

//排除会员
function initTable22() {
    $.ajax({

        url:root.member.listIntegralExclude,
        cache: false,  //禁用缓存
        contentType: 'application/x-www-form-urlencoded',
        type: "post",
        data: {
            pageNum: 1,
            pageSize: 1000000,
            loginAccount:$("#loginAccount").val(),
            mobile: $("#mobile").val(),

        },
        success: function (data) {
            excutTabls(data.data.result, 0);
            $('.M-box3').pagination({
                pageCount: data.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.member.listIntegralExclude,
                        cache: false,  //禁用缓存
                        cache: false, //禁用缓存
                        contentType: 'application/x-www-form-urlencoded',
                        type: "post",
                        data: {
                            pageNum: api.getCurrent(),
                            pageSize: 1000000,
                            loginAccount:$("#loginAccount").val(),
                            mobile: $("#mobile").val(),
                        },
                        success: function (result) {
                            excutTabls(result.data.result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
function excutTabls(data) {

    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0,dataSource.length);//清空数组


    $.each(data, function (i, field) {
        var rowData = new Array();
        rowData.push(field.index);
        rowData.push(field.loginAccount);
       /* rowData.push(field.mobile);
        rowData.push(field.levelName);*/
        rowData.push(field.remarks);
        rowData.push(field.excludeId);
        dataSource.push(rowData);

    });

    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#excludetable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#excludetable").DataTable({
            "fnDrawCallback" : function(){
                this.api().column(0).nodes().each(function(cell,i){
                    //权限控制函数
                    power()
                });
            },
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": true,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": false,
            "aLengthMenu": [10],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },

/*
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },*/
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<a class="powerButton 498" onclick="deleteall(\''+row[3]+'\')">删除</a>'

                        return val;
                    },
                    "targets": 3
                },



            ]
        });
//权限控制函数
        power()
    };
}

//删除
function deleteall(id) {
    $.ajax({
        url:root.member.deleteIntegralExclude,
        cache: false,  //禁用缓存
        contentType: 'application/x-www-form-urlencoded',
        type: "post",
        data: {
            excludeId: id,

        },
        success: function (data) {
          if(data.errorCode==0){
              $.Huimodalalert('删除成功！',2000);
              initTable22()
       }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}